package com.echo.code.demo;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.Objects;

/**
 * Created by baiyp on 2019/05/16.
 */
@MultipartConfig(location = "/Users/mac/Log/tmp/", maxFileSize = 1024 * 1024 * 10)
@WebServlet(name = "upload", urlPatterns = "/upload")
@Log4j2
public class UploadServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        try {
            Part part = req.getPart("file");
            String filename = getFilename(part);
            log.info("the file name is {}" , filename);
            part.write(filename);
        } catch (Exception e) {
            log.error(e);
        }
        log.warn("dispatching...");
        RequestDispatcher rd = req.getRequestDispatcher("index.jsp");
        rd.forward(req, resp);
    }

    // get the fie name
    private String getFilename(Part part) {
        if (Objects.isNull(part)) {
            return null;
        }
        String fileName = part.getHeader("content-disposition");
        if (StringUtils.isBlank(fileName)) {
            return null;
        }
        return StringUtils.substringBetween(fileName, "filename=\"", "\"");
    }
}






